package com.naiterui.ehp.bs.pharmacist.interceptor;

import com.naiterui.ehp.bp.support.context.ResourceHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author guoyongxiang
 * @date 2019-01-15 10:40
 * @since 1.0.0
 */
public class LogCostInterceptior implements HandlerInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(LogCostInterceptior.class);

    private static final String REQ_START = "req_start";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        ResourceHolder.bindResource(REQ_START, System.currentTimeMillis());
//        LOGGER.debug("REQUEST_TRACE, {}", getParamsStr(request));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        Long start = (Long) ResourceHolder.getResource(REQ_START);
        String uri = request.getRequestURI();
        Long patientId = UserUtils.getUser().getPatientId();
        Long doctorId = UserUtils.getUser().getDoctorId();

        if (patientId != null && doctorId != null) {
            LOGGER.info("请求地址 uri:{}, patientId:{}, doctorId:{}, cost:{}", uri, patientId, doctorId, System.currentTimeMillis() - start);
        } else if (patientId != null) {
            LOGGER.info("请求地址 uri:{}, patientId:{}, cost:{}", uri, patientId, System.currentTimeMillis() - start);
        } else if (doctorId != null) {
            LOGGER.info("请求地址 uri:{}, doctorId:{}, cost:{}", uri, doctorId, System.currentTimeMillis() - start);
        } else {
            LOGGER.info("请求地址 uri:{}, cost:{}", uri, System.currentTimeMillis() - start);
        }
        ResourceHolder.clear();
    }

    /**
     * 获取请求参数
     *
     * @param request
     * @param parameterNames
     *
     * @return
     */
    protected Map<String, List<String>> getParameter(HttpServletRequest request, Enumeration<String> parameterNames) {
        Map<String, List<String>> parameterMaps = new HashMap<>();
        while (parameterNames.hasMoreElements()) {
            String paramName = parameterNames.nextElement();
            String[] parameterValues = request.getParameterValues(paramName);
            if (parameterValues != null && parameterValues.length > 0) {
                parameterMaps.put(paramName, Arrays.asList(parameterValues));
            }
        }
        return parameterMaps;
    }

}
